﻿using BigFileUploadDemo.RRModels;
using System;
using System.IO;
using System.Linq;

namespace BigFileUploadDemo.Lib
{
    public class FIleLib
    {
        /// <summary>
        /// 合并文件
        /// </summary>
        /// <param name="md5"></param>
        /// <param name="fileName"></param>
        /// <param name="basdir"></param>
        /// <returns></returns>
        public bool MergeFileForClient(string md5, string fileName, string basdir)
        {
            bool ok = false;
            try
            {
                //临时文件夹
                var temporary = Path.Combine(basdir, md5);
                //获得下面的所有分片文件
                var files = Directory.GetFiles(temporary);
                //指定最终存储路径
                string finalPath = $"{basdir}\\{DateTime.Now.ToString("yyyyMM")}\\{md5}";
                if (!Directory.Exists(finalPath))
                    Directory.CreateDirectory(finalPath);
                finalPath += $"\\{fileName}";
                using (var fs = new FileStream(finalPath, FileMode.Create))
                {
                    foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序，保证从0-N Write
                    {
                        var bytes = File.ReadAllBytes(part);
                        fs.Write(bytes, 0, bytes.Length);
                        bytes = null;
                        File.Delete(part);//删除分块
                    }
                    fs.Flush();
                    fs.Close();
                }
                //删除临时文件夹
                Directory.Delete(temporary);            
                ok = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"文件合并出错，{ex.Message},{ex.StackTrace}");
                return false;
            }
            return ok;
        }

        /// <summary>
        /// 合并文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="md5">md5值</param>
        /// <param name="basepath">基础路径</param>
        /// <returns></returns>
        public UploadResponseModel MergeFileForWeb(string fileName, string md5, string basepath)
        {
            var UploadResponseModel = new UploadResponseModel();
            //临时文件夹
            var dir = Path.Combine(basepath, md5);
            //获得下面的所有文件
            var files = Directory.GetFiles(dir);
            var yearMonth = DateTime.Now.ToString("yyyyMM");
            //最终的文件名
            var finalDir = Path.Combine(basepath, yearMonth, md5);
            if (!Directory.Exists(finalDir))
                Directory.CreateDirectory(finalDir);
            var finalPath = Path.Combine(finalDir, fileName);

            using (var fs = new FileStream(finalPath, FileMode.Create))
            {
                //排一下序，保证从0-N Write
                var fileParts = files.OrderBy(x => x.Length).ThenBy(x => x);
                foreach (var part in fileParts)
                {
                    var bytes = System.IO.File.ReadAllBytes(part);
                    fs.Write(bytes, 0, bytes.Length);
                    bytes = null;
                    //删除分块
                    File.Delete(part);
                }
                fs.Flush();
                fs.Close();
                //删除临时文件夹和分片文件
                Directory.Delete(dir);
                UploadResponseModel.url = $"/upfile/{yearMonth}/{md5}/{fileName}";
                UploadResponseModel.uploadid = Guid.NewGuid().ToString("N");
            }
            return UploadResponseModel;
        }
    }
}
